#!/usr/bin/env bash
set -e
set -u
set -o pipefail


get_desc() {
    echo $(sed -n -e 's/<meta name=\"description\" content=\"//p' $1 | sed -n -e 's/\"//p')
}


get_link() {
    echo ${1:1}
}


get_date() {
    echo $(sed -n '/<p class=\"date\">Date:/,/<\/p>/p; /<\/p>/q' $1 \
	       | sed -n -e 's/<\/p>//p' \
	       | sed -n -e 's/<p class=\"date\">Date: //p' \
	)
}


get_titl() {
    echo $(sed -n -e 's/<title>//p' $1 | sed -n -e 's/<\/title>//p')
}


generate_rss_main() {
    local name=${1:-Site}
    local max_entries=${2:-10}
    local file=feeds/file.rss.xml

    if [[ ! $max_entries =~ ^-?[0-9]+$ ]] || [ "$max_entries" -lt 1 ]; then
	echo "Must have at least one entry, defaulting to 1."
	max_entries=1
    fi
    if [ ! -d feeds ]; then
        mkdir feeds
    fi
    if [ -f "$file" ]; then
        rm ${file}
    else
        echo "Create new rss feed."
    fi
    touch ${file}


    echo "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" >> ${file}
    echo -e "<rss version=\"2.0\">\n  <channel>" >> ${file}
    echo -e "    <description/>" >> ${file}
    echo -e "    <lastBuildDate>$(date)</lastBuildDate>" >> ${file}
    echo -e "    <link>/</link>" >> ${file}
    echo -e "    <title>${name}</title>" >> ${file}

    local array=()
    local arra2=()
    while IFS=  read -r -d $'\0'; do
        array+=("$REPLY")
    done < <(find . -type f -name "*.html" -print0)


    for i in "${array[@]}"
    do
        arra2+=("`get_date $i`|`get_titl $i`|`get_desc $i`|`get_link $i`")
    done


    IFS=$'\n' sorted=($(sort --reverse <<<"${arra2[*]}")); unset IFS
    for j in "${sorted[@]}"
    do
	if [ "$max_entries" -lt 1 ]; then
	    break
	fi
        IFS='|' read -ra faux <<< "$j"
        if [ ! -z "${faux[0]}" ]; then
	    max_entries=$((max_entries-1))
            echo -e "    <item>" >> ${file}
            echo -e "      <pubDate>${faux[0]}</pubDate>" >> ${file}
            echo -e "      <description>${faux[2]}</description>" >> ${file}
            echo -e "      <link>${faux[3]}</link>" >> ${file}
            echo -e "      <title>${faux[1]}</title>" >> ${file}
            echo -e "    </item>" >> ${file}
        fi
    done

    echo -e "  </channel>\n</rss>" >> ${file}
}

generate_rss_main $@
